<!-- 登录 -->
<template>
    <div class="login_content flex" v-loading="loading">
        <div class="login_img">
            <img src="/img/login.png" alt="" />
            <div class="login_img_main">
                <p class="login_img_main_p1">人力资源管理系统</p>
                <p class="login_img_main_p2">Human Resources Management System</p>
            </div>
        </div>
        <div class="login_right">
            <div class="login_main">
                <div class="login_main_header">
                    <p>人力资源管理系统</p>
                    <p>Human Resources Management System</p>
                </div>
                <!-- 登录 -->
                <div class="login_mains" v-if="loginValue == 0">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm-login">
                        <p class="login_mains_title">登录</p>
                        <el-form-item label="" prop="phone" class="el-form-item-login">
                            <el-input  v-model="ruleForm.phone" clearable placeholder="请输入手机号"></el-input>
                        </el-form-item>
                        <el-form-item label="" prop="password" class="el-form-item-login">
                            <el-input v-model="ruleForm.password" clearable class="el-input-login" placeholder="请输入密码"
                                show-password></el-input>
                        </el-form-item>
                        <el-form-item label="" prop="code" class="el-form-item-login">
                            <div class="flex yanzhneg">
                                <div class="" style="width: 70%;">
                                    <el-input placeholder="请输入验证码" clearable v-model="ruleForm.code"></el-input>
                                </div>
                                <img style="height: 100%;margin: 0;" @click="getImage()" :src="imageUrl" alt="" srcset="">
                            </div>
                        </el-form-item>

                        <div class="flex jcsb aic" style="margin-top: 53px;">
                            <el-checkbox v-model="remember">记住账号密码</el-checkbox>
                            <nuxt-link :to="'login?id=forget'">
                                <span class="fonts18 fontz" style="color: #2F6CBC;" @click="loginValue = 2">忘记密码?</span>
                            </nuxt-link>

                        </div>
                        <div class="flex" style="margin-top: 62px;">
                            <el-button type="primary" style="width: 100%;" @click="login('ruleForm')">登录</el-button>
                        </div>
                        <div class="flex jcc aic" style="margin-top: 30px;">
                            <nuxt-link :to="'login?id=register'"><span class="fonts18 fontz" style="color: #2F6CBC;"
                                @click="urlClick()">还没有账号？去注册</span></nuxt-link>

                        </div>
                    </el-form>
                </div>
                <!-- 注册 -->
                <div class="login_mains" v-if="loginValue == 1">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm-login">
                        <p class="login_mains_title">注册</p>
                        <el-form-item label="" prop="phone" class="el-form-item-login">
                            <el-input v-model="ruleForm.phone" clearable placeholder="请输入手机号"></el-input>
                        </el-form-item>
                        <el-form-item label="" prop="code" class="el-form-item-login">
                            <el-input v-model="ruleForm.code" placeholder="请输入验证码">
                                <div class="" style="line-height: 60px;" slot="suffix">
                                    <span v-show="show" class=" fontz fonts18" style="color: #2F6CBC;margin-right: 20px;"
                                        @click="getYan('ruleForm')">{{ text }}</span>
                                    <span v-show="!show" class=" fontz fonts18"
                                        style="color: #2F6CBC;margin-right: 20px;">{{ count }}s</span>
                                </div>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="" prop="password" class="el-form-item-login">
                            <el-input v-model="ruleForm.password" clearable class="el-input-login" placeholder="请输入密码"
                                show-password></el-input>
                        </el-form-item>
                        <el-form-item label="" prop="passwords" class="el-form-item-login">
                            <el-input v-model="ruleForm.passwords" clearable class="el-input-login" placeholder="请再次输入密码"
                                show-password></el-input>
                        </el-form-item>
                        <div class="flex jcsb aic" style="margin-top: 53px;">
                            <el-checkbox v-model="checked">同意<span style="color: #2F6CBC;">《用户注册协议》</span></el-checkbox>
                        </div>
                        <div class="flex" style="margin-top: 62px;">
                            <el-button type="primary" style="width: 100%;" @click="resect('ruleForm')">注册</el-button>
                        </div>
                        <div class="flex jcc aic" style="margin-top: 30px;margin-bottom: 100px;">
                            <nuxt-link :to="'login?id=login'">
                                <span class="fonts18 fontz" style="color: #2F6CBC;" @click="urlClick()">已有账号？去登录</span>
                            </nuxt-link>

                        </div>

                    </el-form>
                </div>
                <!-- 忘记密码 -->
                <div class="login_mains" v-if="loginValue == 2">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm-login">
                        <p class="login_mains_title">忘记密码</p>
                        <el-form-item label="" prop="phone" class="el-form-item-login">
                            <el-input v-model="ruleForm.phone" clearable placeholder="请输入手机号"></el-input>
                        </el-form-item>
                        <el-form-item label="" prop="code" class="el-form-item-login">
                            <el-input v-model="ruleForm.code" placeholder="请输入验证码">
                                <div class="" style="line-height: 60px;" slot="suffix">
                                    <span v-show="show" class=" fontz fonts18" style="color: #2F6CBC;margin-right: 20px;"
                                        @click="getYan('ruleForm')">{{ text }}</span>
                                    <span v-show="!show" class=" fontz fonts18"
                                        style="color: #2F6CBC;margin-right: 20px;">{{ count }}s</span>
                                </div>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="" prop="password" class="el-form-item-login">
                            <el-input v-model="ruleForm.password" clearable class="el-input-login" placeholder="请输入密码"
                                show-password></el-input>
                        </el-form-item>
                        <el-form-item label="" prop="passwords" class="el-form-item-login">
                            <el-input v-model="ruleForm.passwords" clearable class="el-input-login" placeholder="请再次输入密码"
                                show-password></el-input>
                        </el-form-item>
                        <div class="flex" style="margin-top: 62px;">
                            <el-button type="primary" style="width: 100%;" @click="change('ruleForm')">确定修改</el-button>
                        </div>
                        <div class="flex jcc aic" style="margin-top: 30px;margin-bottom: 100px;">
                            <nuxt-link :to="'login?id=login'">
                                <span class="fonts18 fontz" style="color: #2F6CBC;"  @click="urlClick()">去登录</span>
                            </nuxt-link>
                        </div>
                    </el-form>

                </div>
            </div>
        </div>


    </div>
</template>
<script>
import { getLogin, getInfo, get_reg_sms, get_reg_code, restPassword, person_register, checkPhoneUnique } from "@/api/login";
import CryptoJS from 'crypto-js';
export default {
    data() {
        var checkPhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("手机号不能为空"));
            } else {
                const reg = /^1[3-9][0-9]\d{8}$/;
                // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
                if (reg.test(value)) {
                    callback();
                } else {
                    // 具体错误信息没有提示
                    return callback(new Error("请输入正确的手机号"));
                }
            }
        };
        return {
            show: true,
            count: 60,
            text: '获取验证码',
            timer: null,
            loading: false,
            uuid: "",
            btnTxt: "获取验证码",
            remember: true,
            // 是否禁用  即点击之后一段时间内无法再点击
            disabled: false,
            time: 0,
            loginValue: 0,
            input: "",
            checked: false,
            imageUrl: "",
            ruleForm: {
                phone: "",
                password: "",
                code: "",
                passwords: ""
            },
            rules: {
                phone: [{
                    required: true,
                    message: '请输入手机号',
                    trigger: 'blur'
                }, {
                    validator: checkPhone,
                    trigger: "blur"
                }],
                password: [{
                    required: true,
                    message: '请输入密码',
                    trigger: 'blur'
                }],
                passwords: [{
                    required: true,
                    message: '请再次输入密码',
                    trigger: 'blur'
                }],
                code: [{
                    required: true,
                    message: '请输入验证码',
                    trigger: 'blur'
                }]
            }
        }
    },
    created() {
        this.loading = true
    },
    mounted() {
        console.log(1111);
        var myid = this.getUrlParams().id
        if (myid == 'login') {
            console.log("登录");
            this.loginValue = 0
            this.clean()
            this.ruleForm.phone = localStorage.getItem('newHrWeb-username') ? localStorage.getItem('newHrWeb-username') : ''
            this.ruleForm.password = this.decryptPassword() ? this.decryptPassword() : ''
            this.getImage()
        } else if (myid == 'register') {
            this.clean()
            this.loginValue = 1
            this.loading = false
        } else {
            this.clean()
            this.loginValue = 2
            this.loading = false
        }
    },
    methods: {
        urlClick(){
            setTimeout(() => {
                location.reload()
            }, 100);
        },
        clean() {
            this.ruleForm.code = "";
            this.ruleForm.phone = "";
            this.ruleForm.password = "";
            this.ruleForm.passwords = ""
        },
        // 解密密码  
        decryptPassword() {
            let password = localStorage.getItem("newHrWeb-password") ? localStorage.getItem("newHrWeb-password") : ""
            if (password) {
                password = JSON.parse(password)
                const bytes = CryptoJS.AES.decrypt(password, 'mySecretKeyL');
                const originalPassword = bytes.toString(CryptoJS.enc.Utf8);
                return originalPassword
            } else {
                return ""
            }


        },
        // 加密密码  
        encryptPassword(message) {
            const maskedPassword = CryptoJS.AES.encrypt(message, 'mySecretKeyL').toString();
            localStorage.setItem("newHrWeb-password", JSON.stringify(maskedPassword))
        },
        getUrlParams() {
            let url = window.location.search; //获取url中"?"符后的字串
            let paramsObj = new Object();
            if (url.indexOf("?") != -1) {
                let str = url.substr(1);
                let strs = str.split("&");
                for (let i = 0; i < strs.length; i++) {
                    paramsObj[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
                }
            }
            return paramsObj;
        },
        change(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.ruleForm.password != this.ruleForm.passwords) {
                        this.$message({ message: "两次密码不一致", type: 'error' });
                        return
                    }

                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            let params = {
                                "clientId": "1b45e327bb9e739fa094eabd04b1140f",
                                "grantType": "phonePassword",
                                "tenantId": "000001",
                                "password": this.ruleForm.password,
                                "phonenumber": this.ruleForm.phone,
                                "smsCode": this.ruleForm.code,
                            }
                            restPassword(params).then(res => {
                                console.log(res.data);
                                if (res.code == 200) {
                                    this.$message({ message: "重置成功", type: 'success' });
                                    setTimeout(() => {
                                        this.$router.push("login?id=login")
                                        this.loginValue = 0
                                        this.clean()
                                        this.ruleForm.phone = localStorage.getItem('newHrWeb-username') ? localStorage.getItem('newHrWeb-username') : ''
                                        this.ruleForm.password = this.decryptPassword() ? this.decryptPassword() : ''
                                        this.getImage()
                                    }, 500)
                                } else {
                                    this.$message({ message: res.msg, type: 'error' });
                                }
                            })
                        } else {
                            console.log('error submit!!');
                            return false;
                        }
                    })
                }

            })
        },
        getYan(formName) {
            this.$refs[formName].validateField("phone", (res) => {
                console.log(res);
                if (!res) {
                    const TIME_COUNT = 60;
                    if (!this.timer) {
                        this.count = TIME_COUNT;
                        this.show = false;
                        this.timer = setInterval(() => {
                            if (this.count > 0 && this.count <= TIME_COUNT) {
                                this.count--;
                            } else {
                                this.show = true;
                                this.text = "重新获取"
                                clearInterval(this.timer);
                                this.timer = null;
                            }
                        }, 1000)
                    }
                    console.log("进来了");
                    let obj = {
                        phonenumber: this.ruleForm.phone
                    }
                    get_reg_sms(obj).then(res => {
                        console.log(res.msg);
                        if (res.code == 200) {
                            this.$message({ message: res.msg, type: 'success' });
                        } else {
                            this.$message({ message: res.msg, type: 'error' });
                        }
                    })
                } else {

                }

            })
        },
        login(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let obj = {
                        "clientId": "1b45e327bb9e739fa094eabd04b1140f",
                        "grantType": "phonePassword",
                        "tenantId": "000001",
                        "password": this.ruleForm.password,
                        "phonenumber": this.ruleForm.phone,
                        "code": this.ruleForm.code,
                        "uuid": this.ruleForm.uuid,
                    }
                    this.loading = true
                    getLogin(obj).then((res) => {
                        console.log(res);
                        this.loading = false
                        if (res.code == 200) {
                            if (this.remember) {
                                localStorage.setItem('newHrWeb-username', this.ruleForm.phone);
                                this.encryptPassword(this.ruleForm.password)
                            } else {
                                localStorage.removeItem('newHrWeb-username');
                                localStorage.removeItem('password');
                            }

                            sessionStorage.setItem("userInfoData_web", JSON.stringify(res.data))
                            //    this.$cookies.set('userInfoData_web', res.data)
                            sessionStorage.setItem("loginBool", true)
                            this.$message({
                                message: '登录成功',
                                type: 'success'
                            });
                            this.getInfo_()
                            // return
                            setTimeout(() => {
                                this.$router.push("index2")
                            }, 500)
                        } else {
                            this.loading = false
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    }).catch(res=>{
                        this.loading = false
                    })
                } else {
                    this.loading = false
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        getInfo_() {
            getInfo().then(res => {
                console.log("个人信息", res);
                sessionStorage.setItem("myInfornation", JSON.stringify(res.data))
            })
        },
        getImage() {
            get_reg_code().then(res => {
                // console.log(res);
                this.loading = false
                this.imageUrl = "data:image/jpeg;base64," + res.data.img
                this.uuid = res.data.uuid
            })
        },
        resect(formName) {
            if (this.ruleForm.password != this.ruleForm.passwords) {
                this.$message({ message: "两次密码不一致", type: 'error' });
                return
            }
            if (!this.checked) {
                this.$message({ message: "请先同意用户协议", type: 'error' });
                return
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    checkPhoneUnique(this.ruleForm.phone).then(res => {
                        if (res.data) {
                            let params = {
                                "clientId": "1b45e327bb9e739fa094eabd04b1140f",
                                "grantType": "phonePassword",
                                "tenantId": "000001",
                                "password": this.ruleForm.password,
                                "phonenumber": this.ruleForm.phone,
                                "smsCode": this.ruleForm.code,
                                "userType": "application_user"
                            }
                            person_register(params).then(res => {
                                console.log(res.data);
                                if (res.code == 200) {
                                    this.$message({ message: "注册成功", type: 'success' });
                                    setTimeout(() => {
                                        this.$router.push("login?id=login")
                                        this.loginValue = 0
                                        this.clean()
                                        this.ruleForm.phone = localStorage.getItem('newHrWeb-username') ? localStorage.getItem('newHrWeb-username') : ''
                                        this.ruleForm.password = this.decryptPassword() ? this.decryptPassword() : ''
                                        this.getImage()
                                    }, 500)
                                } else {
                                    this.$message({ message: res.msg, type: 'error' });
                                }

                            })
                        } else {
                            this.$message({ message: "手机号已注册", type: 'error' });
                        }



                    }).catch((res => {
                        uni.showToast({
                            title: res.msg,
                            icon: 'error'
                        })
                        return
                    }))

                } else {
                    console.log('error submit!!');
                    return false;
                }
            })

        },

    }
}
</script>

<style lang="scss" scoped>
.login_content {


    .login_img {
        width: 48%;
        position: relative;

        .login_img_main {
            position: absolute;
            width: 100%;
            height: 100%;
            left: 0;
            top: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding-left: 108px;

            .login_img_main_p1 {
                width: 80%;
                font-size: 4rem;
                font-family: 'Source Han Sans CN-Bold, Source Han Sans CN';
                font-weight: 700;
                color: #FFFDFD
            }

            .login_img_main_p2 {
                width: 80%;
                font-size: 2.5rem;
                font-family: 'Source Han Sans CN-Bold, Source Han Sans CN';
                font-weight: 700;
                color: #FFFFFF;
            }

        }

        img {
            width: 100%;
            height: 100vh;
        }
    }

}
::v-deep .el-input{
    height: 60px;
    .el-input__inner{
        height: 60px;
    }
}
.login_right {
    width: 52%;
    padding-left: 10%;
    display: flex;
    flex-direction: column;
}

.login_main {
    // overflow-y: auto;
    max-height: 100vh;
    // background-color: #3D3D3D;
    white-space: nowrap;

    .login_right {
        width: 52%;
    }
}

.login_main_header {
    margin-top: 103px;

    p {
        &:nth-child(1) {
            font-size: 40px;
            font-family: ' Source Han Sans CN-Bold, Source Han Sans CN';
            font-weight: 700;
            color: #2F6CBC;
        }

        &:nth-child(2) {
            font-size: 25px;
            font-family: 'Arial-Regular', Arial;
            font-weight: 400;
            color: #3D3D3D;
        }
    }
}


.login_mains {
    margin-top: 70px;
    width: 70%;
    .login_mains_title {
        font-size: 22px;
        font-family: 'Source Han Sans CN-Bold, Source Han Sans CN';
        font-weight: 700;
        color: #3D3D3D;
    }
}

.yanzhneg {
    width: 100%;
    align-items: center;
    justify-content: space-between;

    img {
        margin-top: 20px;
        width: 28%;
        height: 60px;
        border-radius: 8px 8px 8px 8px;
        opacity: 1;
        border: 1px solid #2F6CBC;
    }
}
</style>